import axios from 'axios'
import { cloneDeep } from 'lodash'
import { safe } from '.'
import { ContactModel } from '~/model/ContactModel'
import { ContactSerializer } from '~/serializer/ContactSerializer'

export class ContactModelWithIsConsumer extends ContactModel {
  is_consumer = false
}

// 用户相关接口
export abstract class ContactApi {
  private static quering?: Promise<ContactModel[]>
  private static cache?: ContactModel[]
  private static clearCache() {
    delete this.quering
    delete this.cache
  }

  public static async getAll(): Promise<ContactModel[]> {
    // use cache
    if (this.cache) {
      return cloneDeep(this.cache)
    }

    // pend
    if (this.quering) {
      return await this.quering
    }

    const inner: () => Promise<ContactModel[]> = async () => {
      const res = await axios.get('contacts/')
      const arr = await res.data
      const ret = arr.map((x: any) => ContactSerializer.deserialize(x))
      ContactApi.cache = ret
      return ret
    }

    this.quering = inner()
    return await this.quering
  }

  public static async getWithIsConsumer(): Promise<ContactModelWithIsConsumer[]> {
    const res = await axios.get('contacts/get_with_isconsumer/')
    const arr = await res.data
    const ret = arr.map((x: any) => {
      const a = ContactSerializer.deserialize(x)
      a.is_consumer = x.is_consumer
      return a
    })
    return ret
  }

  public static async add(
    contact: ContactModel,
  ): Promise<boolean> {
    ContactApi.clearCache()
    return safe(() => axios.post(
      'contacts/',
      ContactSerializer.serialize(contact),
    ))
  }

  public static async remove(
    id: number,
  ): Promise<boolean> {
    ContactApi.clearCache()
    return safe(() => axios.delete(
      `contacts/${id}/`,
    ))
  }

  public static async update(
    id: number,
    contact: ContactModel,
  ): Promise<boolean> {
    ContactApi.clearCache()
    return safe(() => axios.put(
      `contacts/${id}/`,
      ContactSerializer.serialize(contact),
    ))
  }

  public static async uploadAvatar(id: number, image: Blob) {
    ContactApi.clearCache()

    const fd = new FormData()
    fd.append('avatar', image)

    return safe(() => axios.post(
      `contacts/${id}/upload_avatar/`,
      fd,
    ))
  }

  public static async addBatch(contacts: ContactModel[]) {
    ContactApi.clearCache()

    const data = contacts.map(x => ContactSerializer.serialize(x))
    return safe(() => axios.put(
      'contacts/add_batch/',
      data,
    ))
  }
}
